package com.zrc.ke.core;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ProxyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            String className = intent.getStringExtra("className");
            Class serviceClass = PluginManager.getInstance(this).getDexClassLoader().loadClass(className);
            Object service = serviceClass.newInstance();
//            ServiceInterface serviceInterface = (ServiceInterface) service;
//            serviceInterface.insertAppContext(this);
//            serviceInterface.onStartCommand(intent,flags,startId);
            invokeMethod(serviceClass,service,true,"insertAppContext", new Class[]{Service.class}, new Object[]{this});
            invokeMethod(serviceClass,service,true,"onStartCommand", new Class[]{Intent.class,int.class, int.class,}, new Object[]{intent,flags,startId});
        } catch ( Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void invokeMethod(Class localClass, Object activity, Boolean isPublic, String methodName, Class[] parmsClass, Object[] parms) {
        try {
            Method method;
            if (isPublic) {
                method = localClass.getMethod(methodName, parmsClass);
            } else {
                method = localClass.getDeclaredMethod(methodName, parmsClass);
            }
            method.setAccessible(true);
            if (method != null) {
                method.invoke(activity, parms);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
